﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Weather.BLL.Common;
using Weather.BLL.Entity;
using Weather.BLL.Weather;
using Weather.BLL.Weixin;
using Weather.DAL.CoWeather;
using Tilver.Common;

namespace Weather.Wap.Controllers
{
    using System.Text.RegularExpressions;

    public class WapController : Controller
    {
        Tilver.Common.ILogger _logger = Tilver.Common.LoggerFactory.Create();
        public ActionResult Index(string stationNum)
        {
            try
            {
                if (!string.IsNullOrEmpty(stationNum))
                {
                    var info = new WeatherBO().GetAutoStationInfoDO(stationNum);
                    ViewBag.StationName = info == null ? string.Empty : info.Coder站名;
                }

            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }

            ViewBag.StationNum = stationNum;
            return View();
        }

        #region 潮汐
        public ActionResult Tide()
        {
            ViewBag.CurDate = DateTime.Now.ToString("yyyy-MM-dd");
            return View();
        }
        public ActionResult TideJson(string stationNum)
        {
            //var queryDate = DateTime.Now.ToString("yyyy-MM-dd");
            var queryDate = Utils.GetQueryString("querydate").ToDateTime(DateTime.Now).ToString("yyyy-MM-dd");
            var ret = new List<List<string>>();
            try
            {
                var bo = new WeatherBO();
                var list = bo.GetWeatherTideInfoDO(stationNum,DateTime.Now.Date);
                if (list.Any())
                {
                    var l = list.First();
                    queryDate = l.date.Date.ToString("yyyy-MM-dd");
                    for (int i = 0; i < 24; i++)
                    {
                        var k = BLL.Common.Utils.ConvertToUnixTime(l.date.Date.AddHours(i)).ToString() + "000";
                        var v = 0;
                        #region TH
                        switch (i)
                        {
                            case 0:
                                v = l.TH0;
                                break;
                            case 1:
                                v = l.TH1;
                                break;
                            case 2:
                                v = l.TH2;
                                break;
                            case 3:
                                v = l.TH3;
                                break;
                            case 4:
                                v = l.TH4;
                                break;
                            case 5:
                                v = l.TH5;
                                break;
                            case 6:
                                v = l.TH6;
                                break;
                            case 7:
                                v = l.TH7;
                                break;
                            case 8:
                                v = l.TH8;
                                break;
                            case 9:
                                v = l.TH9;
                                break;
                            case 10:
                                v = l.TH10;
                                break;
                            case 11:
                                v = l.TH11;
                                break;
                            case 12:
                                v = l.TH12;
                                break;
                            case 13:
                                v = l.TH13;
                                break;
                            case 14:
                                v = l.TH14;
                                break;
                            case 15:
                                v = l.TH15;
                                break;
                            case 16:
                                v = l.TH16;
                                break;
                            case 17:
                                v = l.TH17;
                                break;
                            case 18:
                                v = l.TH18;
                                break;
                            case 19:
                                v = l.TH19;
                                break;
                            case 20:
                                v = l.TH20;
                                break;
                            case 21:
                                v = l.TH21;
                                break;
                            case 22:
                                v = l.TH22;
                                break;
                            case 23:
                                v = l.TH23;
                                break;
                        }
                        #endregion
                        ret.Add(new List<string> { k, v.ToString() });
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }
            /*ret.Add(new List<string> { "1429113600000,207" });
            ret.Add(new List<string> { "1429117200000,407" });
            ret.Add(new List<string> { "1429120800000,107" });*/


            return Content(string.Format("{{\"querydate\":\"{0}\",\"data\":{1}}}", queryDate, Newtonsoft.Json.JsonConvert.SerializeObject(ret).Replace("\"", "")));
        }
        #endregion

        #region 天气预报


        public ActionResult Weather(string stationNum, string fcstType)
        {
            int ft = fcstType.ToInt32();
            var list = new List<FcstTextLocalEO>();
            try
            {
                var bo = new FcstTextLocalBO();
                if (!string.IsNullOrEmpty(stationNum))
                {
                    list = bo.GetFcstTextLocalByStationNum(stationNum);
                    //获取站点信息
                    var info = new WeatherBO().GetAutoStationInfoDO(stationNum);
                    ViewBag.StationName = info == null ? string.Empty : info.Coder站名;
                }

                if (list != null && list.Any(w => w.FcstType == ft))
                {
                    ViewBag.FcstTitle = list.Find(w => w.FcstType == ft).FcstTitle;
                    //ViewBag.FcstText = list.Find(w => w.FcstType == ft).FcstText.Replace("\r\n", "<br/>");
                    var sb = new StringBuilder();
                    var fcstTexts = Regex.Split(list.Find(w => w.FcstType == ft).FcstText, "\r\n", RegexOptions.IgnoreCase);
                    foreach (var fcstText in fcstTexts)
                    {
                        sb.Append("<div style=\"padding:6px;font-size:14px;overflow:hidden;_zoom:1;border-top:1px solid #eceef0;\">");
                        sb.Append("<span>");
                        sb.Append(fcstText);
                        sb.Append("</span>");
                        sb.Append("<div style=\"clear: both;\"></div></div>");
                    }

                    ViewBag.FcstText = sb.ToString();
                }
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }


            ViewBag.StationNum = stationNum;
            ViewBag.FcstType = ft;

            return View();
        }
        #endregion

        #region 卫星云图和雷达图

        public class ProbeImageResult
        {
            /// <summary>
            /// 图片ID
            /// </summary>
            public string Id { get; set; }

            /// <summary>
            /// 站点
            /// </summary>
            public string StationNum { get; set; }

            /// <summary>
            /// 发布时间
            /// </summary>
            public string ObservTime { get; set; }
            /// <summary>
            /// 图片类型
            /// </summary>
            public string Stage { get; set; }

        }
        /// <summary>
        /// 新的查询雷达和云图方式
        /// </summary>
        /// <param name="stationNum"></param>
        /// <param name="fcstType"></param>
        /// <returns></returns>
        public ActionResult ProbePic(string stationNum, string fcstType)
        {
            var queryType = stationNum;//查询类型
            try
            {
                string title = "";
                string ft = "";
                if (queryType.ToLower() == "cloud")
                {
                    title = "卫星云图";
                    switch (fcstType.ToLower())
                    {
                        case "l":
                            ft = "fy2d_l";
                            break;
                        case "m":
                            ft = "fy2d_m";
                            break;
                        case "vis":
                            ft = "fy2d_vis";
                            break;
                    }
                }
                if (queryType.ToLower() == "radar")
                {
                    title = "雷达回波";
                    switch (fcstType.ToLower())
                    {
                        case "zj":
                            ft = "58457";
                            break;
                        case "nb":
                            ft = "58562";
                            break;
                        case "sz":
                            ft = "58556";
                            break;
                    }
                }
                if (queryType.ToLower() == "rain")
                {
                    title = "降水量分布图";
                }
                ViewBag.Title = title;
                //获取站点信息
                /*var info = new WeatherBO().GetAutoStationInfoDO(stationNum);
                ViewBag.StationName = info == null ? string.Empty : info.Coder站名;*/
                ViewBag.StationNum = 58556;
                ViewBag.FcstType = ft;
                ViewBag.QueryType = queryType;

                //获取查询数据
                //var req = Request.QueryString;
                //ViewBag.QueryValue = req.AllKeys.Contains("query") ? req["query"] : string.Empty;
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }
            return View();
        }
        public ActionResult Probe(string stationNum, string fcstType)
        {
            try
            {
                string title = "";
                if (fcstType.ToLower() == "cloud")
                {
                    title = "卫星云图";
                }
                if (fcstType.ToLower() == "radar")
                {
                    title = "雷达回波";
                }
                if (fcstType.ToLower() == "rain")
                {
                    title = "降水量分布图";
                }
                ViewBag.Title = title;
                //获取站点信息
                var info = new WeatherBO().GetAutoStationInfoDO(stationNum);
                ViewBag.StationName = info == null ? string.Empty : info.Coder站名;
                ViewBag.StationNum = stationNum;
                ViewBag.FcstType = fcstType;
                
                //获取查询数据
                var req = Request.QueryString;
                ViewBag.QueryValue = req.AllKeys.Contains("query") ? req["query"] : string.Empty;
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }
            return View();
        }
        public ActionResult ProbeJson(string stationNum, string fcstType)
        {
            string sNum = "05710";
            string[] tem = fcstType.Split('-');
            string queryType = string.Empty;//查询类型
            string imgType = string.Empty;//图片类型
            if (tem.Length == 2)
            {
                queryType = tem[0];
                imgType = tem[1];
            }
            var probeJson = new List<ProbeImageResult>();
            try
            {
                var bo = new ProbeImageBO();
                if (queryType.ToLower() == "cloud")
                {
                    var l = bo.GetCloudImgageDO(imgType);
                    foreach (var probeImageEo in l)
                    {
                        probeJson.Add(new ProbeImageResult()
                        {
                            Id = probeImageEo.Id,
                            StationNum = stationNum,
                            ObservTime = probeImageEo.ObservTime.ToString("yyyy-MM-dd HH:mm"),
                            Stage = imgType
                        });
                    }
                    /*
                    var l = bo.GetProbeImageCloudDO(sNum);
                    foreach (var probeImageCloudEo in l)
                    {
                        var temdate = string.Empty;
                        var d = probeImageCloudEo.Date.ToString();
                        var h = probeImageCloudEo.Time.Trim();
                        if (d.Length == 8 && h.Length == 4)
                            temdate = string.Format("{0}-{1}-{2} {3}:{4}", d.Substring(0, 4), d.Substring(4, 2), d.Substring(6, 2), h.Substring(0, 2), h.Substring(2, 2));
                        probeJson.Add(new ProbeImageResult()
                        {
                            Id = probeImageCloudEo.Id.ToString(),
                            StationNum = probeImageCloudEo.Stationnum,
                            ObservTime = temdate
                        });
                    }*/

                }
                if (queryType.ToLower() == "radar")
                {
                    var l = bo.GetRadarImgageDO(imgType);
                    foreach (var probeImageEo in l)
                    {
                        probeJson.Add(new ProbeImageResult()
                        {
                            Id = probeImageEo.Id,
                            StationNum = stationNum,
                            ObservTime = probeImageEo.ObservTime.ToString("yyyy-MM-dd HH:mm"),
                            Stage = imgType
                        });
                    }
                    //var l = bo.GetProbeImageRadarDO(sNum);
                    //foreach (var probeImageRadarEo in l)
                    //{
                    //    var temdate = string.Empty;
                    //    var d = probeImageRadarEo.Date.ToString();
                    //    var h = probeImageRadarEo.Time.Trim();
                    //    if (d.Length == 8 && h.Length == 4)
                    //        temdate = string.Format("{0}-{1}-{2} {3}:{4}", d.Substring(0, 4), d.Substring(4, 2), d.Substring(6, 2), h.Substring(0, 2), h.Substring(2, 2));
                    //    probeJson.Add(new ProbeImageResult()
                    //    {
                    //        Id = probeImageRadarEo.Id.ToString(),
                    //        StationNum = probeImageRadarEo.Stationnum,
                    //        ObservTime = temdate
                    //    });
                    //}

                }
                if (queryType.ToLower() == "rain")
                {
                    var l = bo.GetProbeImageRainDO(sNum);

                    foreach (var probeImageRainEo in l)
                    {
                        var temdate = string.Empty;
                        var d = probeImageRainEo.Date.ToString();
                        var h = probeImageRainEo.Time.Trim();
                        if (d.Length == 8 && h.Length == 4)
                            temdate = string.Format("{0}-{1}-{2} {3}:{4}", d.Substring(0, 4), d.Substring(4, 2), d.Substring(6, 2), h.Substring(0, 2), h.Substring(2, 2));
                        probeJson.Add(new ProbeImageResult()
                        {
                            Id = probeImageRainEo.Id.ToString(),
                            StationNum = probeImageRainEo.Stationnum,
                            ObservTime = temdate
                        });
                    }

                }


            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }

            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(probeJson));
        }
        /// <summary>
        /// 输出图片
        /// </summary>
        /// <param name="stationNum">查询类型（cloud,radar）</param>
        /// <param name="fcstType">图片ID－图片类型</param>
        /// <returns></returns>
        public ActionResult ProbeImage(string stationNum, string fcstType)
        {
            string sNum = "05710";
            var qt = stationNum;//查询类型
            string[] tem = fcstType.Split('-');
            string it = string.Empty;//图片类型
            string id = string.Empty;//图片ID
            if (tem.Length == 2)
            {
                id = tem[0];
                it = tem[1];
            }
            try
            {
                var bo = new ProbeImageBO();
                if (qt.ToLower() == "cloud")
                {
                    var l = bo.GetCloudImgageDO(it);
                    var t = l.FirstOrDefault(w => w.Id == id);
                    if (t != null)
                    {
                        return File(t.ImgData, string.Format("image/{0}", "png"));
                    }
                    /*var l = bo.GetProbeImageCloudDO(sNum);
                    var t = l.FirstOrDefault(w => w.Id == id.ToInt64(0));
                    if (t != null)
                        return File(t.Data, string.Format("image/{0}", t.Subfix));*/
                }
                if (qt.ToLower() == "radar")
                {
                    var l = bo.GetRadarImgageDO(it);
                    var t = l.FirstOrDefault(w => w.Id == id);
                    if (t != null)
                    {
                        return File(t.ImgData, string.Format("image/{0}", "png"));
                    }
                    //var l = bo.GetProbeImageRadarDO(sNum);
                    //var t = l.FirstOrDefault(w => w.Id == id.ToInt64(0));
                    //if (t != null)
                    //    return File(t.Data, string.Format("image/{0}", t.Subfix));
                }
                if (qt.ToLower() == "rain")
                {
                    var l = bo.GetProbeImageRainDO(sNum);
                    var t = l.FirstOrDefault(w => w.Id == id.ToInt64(0));
                    if (t != null)
                        return File(t.Data, string.Format("image/{0}", t.Subfix));
                }
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }
            return Content("");
        }
        #endregion

        #region 天气地图


        public ActionResult Map(string stationNum, string fcstType)
        {
            try
            {
                int awsType = 0;
                var titleFlag = "天气实况";
                switch (fcstType.ToLower())
                {
                    case "temp":
                        titleFlag = "温度监测";
                        break;
                    case "f":
                        titleFlag = "风力监测";
                        break;
                    case "rain":
                        titleFlag = "降水监测";
                        break;
                    case "visib":
                        awsType = 1;
                        break;
                    case "pm2_5":
                        titleFlag = "PM2.5";
                        break;
                    case "pm10":
                        titleFlag = "PM10";
                        break;
                    default:
                        break;
                }

                var bo = new Weather.BLL.Weixin.WeatherBO();
                var stationInfo = bo.GetAutoStationInfoDO(stationNum);
                var weixin = new BLL.Entity.Weixin();

                if (fcstType.ToLower() == "pm2_5" || fcstType.ToLower() == "pm10")
                {
                    //获取当前空气质量
                    var list = bo.GetWeatherAqiRealTimeInfoDO(stationNum, 0);
                    for (int h = 1; h <= 24; h++)
                    {
                        if (list.Any()) break;
                        list = bo.GetWeatherAqiRealTimeInfoDO(stationNum, h);
                    }
                    if (list.Any())
                    {
                        weixin.Menu = "天气实况";
                        weixin.Title = string.Format("{0}{1}{2}", stationInfo.Coder站名, list.First().observtime.ToString("MM月dd日HH时"), titleFlag);
                        weixin.Image = string.Empty;
                        var content = new List<Station>();
                        foreach (var wi in list)
                        {
                            content.Add(new Station()
                            {
                                Change = new Change
                                {
                                    PM10 = wi.Pm10.ToString(),
                                    PM2_5 = wi.Pm25.ToString()
                                },
                                Id = wi.stationnum,
                                Lat = wi.lat,
                                Lon = wi.lon,
                                Name = wi.stationname
                            });
                        }
                        weixin.Content = content.ToArray();
                        weixin.Rnewtime = list.First().observtime.ToString("yyyy-MM-dd HH:00:00"); //精确到小时
                    }
                }
                else
                {
                    //获取当前实况数据，如果没有取到，就循环取最近24小时的数据，取到为止
                    var list = bo.GetWeatherAwsRealTimeInfoDO(stationNum, 0);
                    for (int h = 1; h <= 24; h++)
                    {
                        if (list.Any()) break;
                        list = bo.GetWeatherAwsRealTimeInfoDO(stationNum, h);
                    }
                    if (list.Any())
                    {
                        weixin.Menu = "天气实况";
                        weixin.Title = string.Format("{0}{1}{2}", stationInfo.Coder站名, list.First().observtime.ToString("MM月dd日HH时"), titleFlag);
                        weixin.Image = string.Empty;
                        var content = new List<Station>();
                        foreach (var wi in list)
                        {
                            //查询风力时，对stationNum为54290单独处理：当风力为0时，不显示数据　2015.04.01
                            if (stationNum == "54290" && fcstType.ToLower() == "f" && wi.ff <= 0) continue;

                            content.Add(new Station()
                            {
                                Change = new Change
                                {
                                    Fd = wi.fd.ToString(),
                                    Ff = (((decimal)wi.ff) / 10).ToString(),
                                    Rain = (((decimal)wi.rain) / 10).ToString(),
                                    Temp = (((decimal)wi.t) / 10).ToString(),
                                    Visibility = wi.v.ToString()
                                },
                                High = wi.rh.ToString(),
                                Id = wi.stationnum,
                                Lat = wi.lat,
                                Lon = wi.lon,
                                Name = wi.stationname
                            });
                        }
                        weixin.Content = content.ToArray();
                        weixin.Rnewtime = list.First().observtime.ToString("yyyy-MM-dd HH:00:00"); //精确到小时
                    }
                }

                var jss = new JavaScriptSerializer();
                ViewBag.WeatherJson = jss.Serialize(weixin);
                ViewBag.WeatherType = fcstType;

                /*
                var xml = bo.GetWeatherXMLDO(stationNum, awsType);
                var o = BLL.Common.XmlSerializer.LoadFromXml(xml, typeof(Weixin));
                var jss = new JavaScriptSerializer();
                ViewBag.WeatherJson = jss.Serialize(o);
                ViewBag.WeatherType = fcstType;
                */

                //获取地区中心点
                var point = bo.GetCenterPointDO(stationNum, awsType);
                ViewBag.Lon = point.Item1;
                ViewBag.Lat = point.Item2;

                //如果是从微信过来的，则不显示页头导航信息
                var v = string.Empty;
                if (Request.QueryString.AllKeys.Contains("v"))
                {
                    v = Request.QueryString["v"];
                }
                ViewBag.V = v;

                //显示样式判断
                var style = string.Empty;
                if (Request.QueryString.AllKeys.Contains("style"))
                {
                    style = Request.QueryString["style"];
                }
                ViewBag.Style = style;
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }

            ViewBag.StationNum = stationNum;
            return View();
        }

        public ActionResult WMap(string stationNum, string fcstType)
        {
            var weathertype = fcstType;
            try
            {
                int awsType = 0;
                if (weathertype.ToLower() == "visib")
                {
                    awsType = 1;
                }
                if (weathertype.ToLower() == "intensity")
                {
                    awsType = 2;
                }

                var bo = new Weather.BLL.Weixin.WeatherBO();
                var xml = bo.GetWeatherXMLDO(stationNum, awsType);
                var o = BLL.Common.XmlSerializer.LoadFromXml(xml, typeof(BLL.Entity.Weixin));
                var jss = new JavaScriptSerializer();
                ViewBag.WeatherJson = jss.Serialize(o);
                ViewBag.WeatherType = weathertype;

                //获取地区中心点
                var point = bo.GetCenterPointDO(stationNum, awsType);
                ViewBag.Lon = point.Item1;
                ViewBag.Lat = point.Item2;

            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }

            return View();
        }
        #endregion

        #region 天气实况

        public ActionResult WLive(string stationNum, string fcstType)
        {
            try
            {
                if (!string.IsNullOrEmpty(stationNum))
                {
                    var info = new WeatherBO().GetAutoStationInfoDO(stationNum);
                    ViewBag.StationName = info == null ? string.Empty : info.Coder站名;
                }

            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }

            ViewBag.StationNum = stationNum;
            ViewBag.FcstType = fcstType;
            return View();
        }

        public ActionResult WLiveGetDataPerhour(string stationNum)
        {
            string[] t = stationNum.Split('-');
            string areaCode = string.Empty;//自动站
            string stationId = string.Empty;//区域站
            if (t.Length == 2)
            {
                areaCode = t[0];
                stationId = t[1];
            }
            return Content(GetWeatherDataPerHour(areaCode, stationId));
        }

        private string GetWeatherDataPerHour(string areaCode, string stationNum)
        {

            var ret = new StringBuilder();
            try
            {
                var bo = new WeatherBO();
                var data = bo.GetWeatherAwsRealTimeInfoDO(areaCode, 1);
                for (int h = 1; h <= 24; h++)
                {
                    if (data.Any()) break;
                    data = bo.GetWeatherAwsRealTimeInfoDO(areaCode, h);
                }

                ret.Append("{");
                var r = data.FirstOrDefault(w => w.stationnum == stationNum);
                if (r != null)
                {
                    ret.AppendFormat("\"stationnun\":\"{0}\",", r.stationnum);
                    ret.AppendFormat("\"stationname\":\"{0}\",", r.stationname);
                    ret.AppendFormat("\"observtime\":\"{0}\",", r.observtime.ToString("yyyyMMddHHmmss"));
                    ret.AppendFormat("\"t\":\"{0}\",", (r.t.ToString().ToDecimal(0) / 10).ToString());
                    ret.AppendFormat("\"rain\":\"{0}\",", (r.rain.ToString().ToDecimal(0) / 10).ToString());
                    ret.AppendFormat("\"v\":\"{0}\",", r.v);
                    ret.AppendFormat("\"ff\":\"{0}\",", (r.ff.ToString().ToDecimal(0) / 10).ToString());
                    ret.AppendFormat("\"fd\":\"{0}\",", r.fd);
                    ret.AppendFormat("\"p\":\"{0}\"", (r.p.ToString().ToDecimal(0) / 10).ToString());
                }
                ret.Append("}");
            }
            catch (Exception ex)
            {
                ret.Append("{}");
                _logger.Write(ex.Message);
            }
            return ret.ToString();
        }

        public ActionResult WLiveGetLineData(string stationNum)
        {
            string[] t = stationNum.Split('-');
            string type = string.Empty;//查询类型
            string areaCode = string.Empty;//自动站
            string stationId = string.Empty;//区域站
            if (t.Length == 3)
            {
                type = t[0];
                areaCode = t[1];
                stationId = t[2];

            }
            return Content(GetWeatherLineData(type, areaCode, stationId));
        }

        protected string GetWeatherLineData(string type, string areaCode, string stationNum)
        {
            var observeType = "气温";
            var json = new StringBuilder();
            var set = new StringBuilder();
            var bo = new WeatherBO();
            var list = bo.GetWeatherRealTimeDataDO(areaCode, stationNum);
            var temL = new List<double>(); //获取温度、风速、雨量里的最大和最小值
            double max = 0;
            double min = 0;
            if (list.Any())
            {
                foreach (var d in list)
                {
                    var t = ConvertUnixToDateTime(d.ObservTimes);
                    var v = d.DryBulTemp;
                    switch (type)
                    {
                        case "temp":
                            observeType = "气温";
                            v = (d.DryBulTemp.ToDecimal(0) / 10).ToString();
                            break;
                        case "rain":
                            observeType = "降雨";
                            v = (d.Precipitation.ToDecimal(0) / 10).ToString();
                            break;
                        case "ff":
                            observeType = "风速";
                            v = (d.ExMaxWindV.ToDecimal(0) / 10).ToString();
                            break;
                    }
                    temL.Add(v.ToDouble(0));
                    set.AppendFormat("<set name='{0}' value='{1}' color='00AEFF' hoverText='{2}' />",
                                     t.Hour, v, t.ToString("yyyy年MM月dd日 HH时"));
                }
                //获取最大最小值
                if (temL.Any())
                {
                    max = temL.Max();
                    min = temL.Min();
                    if (type == "rain" && max == 0 && min == 0)
                    {
                        max = 5;
                    }
                }
                json.AppendFormat("<graph xAxisName='近24小时{0}曲线图' yAxisName='' showNames='1' showValues='0' ",
                                  observeType);
                json.AppendFormat("yAxisMinValue='{0}' yAxisMaxValue='{1}' decimalPrecision='1' ", min, max);
                json.AppendFormat("vDivLineAlpha='30' formatNumberScale='0' canvasBorderColor='b6c6d6' ");
                json.AppendFormat("divLineColor='b6c6d6' canvasBorderThickness='0' lineThickness='1' ");
                json.AppendFormat("baseFontSize='11' canvasBgColor='b6c6d6' bgColor='b6c6d6' ");
                json.AppendFormat("bgAlpha='0' canvasBgAlpha='0' numDivLines='4' numVDivLines='22'>");

                json.AppendFormat(set.ToString());

                json.AppendFormat("</graph>");
            }
            return json.ToString();
        }
        private DateTime ConvertUnixToDateTime(long t)
        {
            System.DateTime time = System.DateTime.MinValue;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            time = startTime.AddSeconds(t);
            return time;
        }


        public ActionResult Live(string stationNum)
        {
            string[] t = stationNum.Split('-');
            string stationNum1 = string.Empty;//自动站
            string stationNum2 = string.Empty;//区域站
            if (t.Length == 2)
            {
                stationNum1 = t[0];
                stationNum2 = t[1];
            }
            try
            {
                //获取自动站点信息
                var autoInfo = new WeatherBO().GetAutoStationInfoDO(stationNum1);
                ViewBag.StationName = autoInfo == null ? string.Empty : autoInfo.Coder站名;
                //获取区域站点信息
                var areaInfo = new WeatherBO().GetAreaStationInfoDO(stationNum2);
                ViewBag.Title = string.Format("{0}天气实况", areaInfo == null ? string.Empty : areaInfo.Coder站名);

                //判断参数来源
                var v = string.Empty;
                if (Request.QueryString.AllKeys.Contains("v"))
                {
                    v = Request.QueryString["v"];
                }
                ViewBag.V = v;
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }

            ViewBag.StationNum = stationNum1;
            ViewBag.StationNum1 = stationNum1;
            ViewBag.StationNum2 = stationNum2;

            return View();
        }

        public ActionResult Temp(string stationNum)
        {

            string[] t = stationNum.Split('-');
            string stationNum1 = string.Empty;//自动站
            string stationNum2 = string.Empty;//区域站
            if (t.Length == 2)
            {
                stationNum1 = t[0];
                stationNum2 = t[1];
            }
            try
            {
                if (!string.IsNullOrEmpty(stationNum2))
                {
                    var bo = new Weather.BLL.Weixin.WeatherBO();
                    var data = bo.GetWeatherRealTimeDataDO(stationNum1, stationNum2);
                    var l = new List<List<string>>();
                    foreach (var weatherRealTimeData in data)
                    {
                        //l.Add(new Tuple<string, string>(weatherRealTimeData.ObservTimes + "000", weatherRealTimeData.DryBulTemp));
                        l.Add(new List<string>() { (weatherRealTimeData.ObservTimes * 1000).ToString(), (weatherRealTimeData.DryBulTemp.ToDecimal(0) / 10).ToString() });
                    }
                    var jss = new JavaScriptSerializer();
                    ViewBag.WeatherRealTimeJson = jss.Serialize(l).Replace("\"", "");
                }
                //获取站点信息
                var info = new WeatherBO().GetAutoStationInfoDO(stationNum1);
                ViewBag.StationName = info == null ? string.Empty : info.Coder站名;
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }
            ViewBag.StationNum = stationNum1;
            return View();
        }
        public ActionResult Rain(string stationNum)
        {
            string[] t = stationNum.Split('-');
            string stationNum1 = string.Empty;//自动站
            string stationNum2 = string.Empty;//区域站
            if (t.Length == 2)
            {
                stationNum1 = t[0];
                stationNum2 = t[1];
            }
            try
            {
                if (!string.IsNullOrEmpty(stationNum2))
                {
                    var bo = new Weather.BLL.Weixin.WeatherBO();
                    var data = bo.GetWeatherRealTimeDataDO(stationNum1, stationNum2);
                    var l = new List<List<string>>();
                    foreach (var weatherRealTimeData in data)
                    {
                        //l.Add(new Tuple<string, string>(weatherRealTimeData.ObservTimes + "000", weatherRealTimeData.Precipitation));
                        l.Add(new List<string>() { (weatherRealTimeData.ObservTimes * 1000).ToString(), weatherRealTimeData.Precipitation });
                    }
                    var jss = new JavaScriptSerializer();
                    ViewBag.WeatherRealTimeJson = jss.Serialize(l).Replace("\"", "");
                }
                //获取站点信息
                var info = new WeatherBO().GetAutoStationInfoDO(stationNum1);
                ViewBag.StationName = info == null ? string.Empty : info.Coder站名;
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }
            ViewBag.StationNum = stationNum1;
            return View();
        }
        public ActionResult Wind(string stationNum)
        {
            //[[1413738000000, 8.5], [1413741600000, 9.2], [1413745200000, 7.0], [1413748800000, 5.3], [1413752400000, 4.7], [1413756000000, 3.7], [1413759600000, 3.3], [1413763200000, 3.1], [1413766800000, 3.3], [1413770400000, 2.1], [1413774000000, 2.6], [1413777600000, 2.3], [1413781200000, 2.4], [1413784800000, 2.4], [1413788400000, 2.3], [1413792000000, 3.3], [1413795600000, 3.5], [1413799200000, 4.3], [1413802800000, 6.6], [1413806400000, 5.9], [1413810000000, 7.3], [1413813600000, 7.4], [1413817200000, 7.8], [1413820800000, 9.0], [1413824400000, 7.9]]
            string[] t = stationNum.Split('-');
            string stationNum1 = string.Empty;//自动站
            string stationNum2 = string.Empty;//区域站
            if (t.Length == 2)
            {
                stationNum1 = t[0];
                stationNum2 = t[1];
            }
            try
            {
                if (!string.IsNullOrEmpty(stationNum2))
                {

                    var bo = new Weather.BLL.Weixin.WeatherBO();
                    var data = bo.GetWeatherRealTimeDataDO(stationNum1, stationNum2);
                    var l = new List<List<string>>();
                    foreach (var weatherRealTimeData in data)
                    {
                        l.Add(new List<string>() { (weatherRealTimeData.ObservTimes * 1000).ToString(), (weatherRealTimeData.ExMaxWindV.ToDecimal(0) / 10).ToString() });
                    }
                    var jss = new JavaScriptSerializer();
                    ViewBag.WeatherRealTimeJson = jss.Serialize(l).Replace("\"", "");
                }
                //获取站点信息
                var info = new WeatherBO().GetAutoStationInfoDO(stationNum1);
                ViewBag.StationName = info == null ? string.Empty : info.Coder站名;
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }
            ViewBag.StationNum = stationNum1;
            return View();
        }
        #endregion

        #region 雨量监测
        public ActionResult Environment(string stationNum)
        {
            try
            {
                //获取站点信息
                var info = new WeatherBO().GetAutoStationInfoDO(stationNum);
                ViewBag.StationName = info == null ? string.Empty : info.Coder站名;
                ViewBag.StationNum = stationNum;
                ViewBag.Title = string.Format("{0}环境监测数据", ViewBag.StationName);

                var bo = new WeatherBO();
                var list = bo.GetWeatherAqiRealTimeInfoDO(stationNum);
                if (list != null)
                    ViewBag.WeatherDataList = list.OrderBy(w => w.stationnum).ToList();
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }
            return this.View();
        }

        #endregion

        #region 环境监测
        public ActionResult RainSurvey(string stationNum)
        {
            try
            {
                //获取站点信息
                var info = new WeatherBO().GetAutoStationInfoDO(stationNum);
                ViewBag.StationName = info == null ? string.Empty : info.Coder站名;
                ViewBag.StationNum = stationNum;
                ViewBag.Title = string.Format("{0}雨量监测数据", ViewBag.StationName);

            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }
            return View();
        }
        public ActionResult RainSurveyData(string stationNum, string fcstType)
        {
            var json = new List<WeatherAwsRealTimeInfo>();
            try
            {
                var bo = new WeatherBO();
                var list = bo.GetWeatherAwsRealTimeInfoDO(stationNum, fcstType.ToInt32(1));
                if (list != null)
                {
                    json = list.OrderBy(w => w.stationnum).ToList();
                }
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }
            var timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "yyyy'-'MM'-'dd HH':'mm" };
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(json, Newtonsoft.Json.Formatting.Indented, timeConverter));
        }
        #endregion

        #region 视频

        public ActionResult Video()
        {
            return View();
        }

        #endregion

        #region 空气质量
        public ActionResult WeatherAQI(string stationNum)
        {
            ViewBag.AreaCode = stationNum;
            int ft = 8;
            try
            {
                if (!string.IsNullOrEmpty(stationNum))
                {
                    var bo = new WeatherBO();
                    var list = bo.GetWeatherAqiStationInfo(stationNum);
                    if (list.Any())
                    {
                        ViewBag.StationList = list;
                        ViewBag.FirstStationNum = list.First().stationnum;
                    }
                    /*var bo = new FcstTextLocalBO();
                    var list = bo.GetFcstTextLocalByStationNum(stationNum);
                    if (list != null && list.Any(w => w.FcstType == ft))
                    {
                        ViewBag.FcstTitle = list.Find(w => w.FcstType == ft).FcstTitle;
                        ViewBag.FcstText = list.Find(w => w.FcstType == ft).FcstText;
                    }*/
                }
            }
            catch (Exception ex)
            {
                _logger.Write(ex.Message);
            }
            return View();
        }

        /// <summary>
        /// 曲线数据返回类
        /// </summary>
        public class WeatherChartDataResult
        {
            public List<string> Times { get; set; }
            public List<double> Values { get; set; }

            public WeatherChartDataResult()
            {
                Times = new List<string>();
                Values = new List<double>();
            }
        }
        public ActionResult WeatherAQIData(string stationNum)
        {
            string[] t = stationNum.Split('-');
            string aqitype = string.Empty;
            string areacode = string.Empty;
            string stationnum = string.Empty;
            if (t.Length == 3)
            {
                aqitype = t[0];
                areacode = t[1];
                stationnum = t[2];
            }
            var ret = new WeatherChartDataResult();

            try
            {
                var bo = new WeatherBO();
                var list = bo.GetWeatherAqiRealTimeInfoByHourDO(areacode, stationnum);
                foreach (var weatherAqiRealTimeInfo in list)
                {
                    switch (aqitype.ToUpper())
                    {
                        case "AQI":
                            ret.Times.Add(weatherAqiRealTimeInfo.observtime.ToString("yyyyMMddHH"));
                            ret.Values.Add(weatherAqiRealTimeInfo.Aqi);
                            break;
                        case "CO":
                            ret.Times.Add(weatherAqiRealTimeInfo.observtime.ToString("yyyyMMddHH"));
                            ret.Values.Add(weatherAqiRealTimeInfo.CO);
                            break;
                        case "NO2":
                            ret.Times.Add(weatherAqiRealTimeInfo.observtime.ToString("yyyyMMddHH"));
                            ret.Values.Add(weatherAqiRealTimeInfo.NO2);
                            break;
                        case "O3":
                            ret.Times.Add(weatherAqiRealTimeInfo.observtime.ToString("yyyyMMddHH"));
                            ret.Values.Add(weatherAqiRealTimeInfo.O3);
                            break;
                        case "PM10":
                            ret.Times.Add(weatherAqiRealTimeInfo.observtime.ToString("yyyyMMddHH"));
                            ret.Values.Add(weatherAqiRealTimeInfo.Pm10);
                            break;
                        case "PM25":
                            ret.Times.Add(weatherAqiRealTimeInfo.observtime.ToString("yyyyMMddHH"));
                            ret.Values.Add(weatherAqiRealTimeInfo.Pm25);
                            break;
                        case "SO2":
                            ret.Times.Add(weatherAqiRealTimeInfo.observtime.ToString("yyyyMMddHH"));
                            ret.Values.Add(weatherAqiRealTimeInfo.SO2);
                            break;
                    }
                }

            }
            catch (Exception ex)
            {
                _logger.Write(ex.StackTrace);
            }
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(ret));
            //return Json(ret);
        }
        #endregion

        #region 上虞所象（试用）
        public ActionResult Syqx()
        {

            ViewBag.QueryTime = DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd");


            try
            {
                var client = new Sxqx.Net.Wxzdz.WxzdzWebServiceSoapClient();
                var qTime = DateTime.Now.AddHours(-1);
                var d = client.GetZdzData("K4501", string.Format("{0}:00:00", qTime.ToString("yyyy-MM-dd HH")).ToDateTime());
                for (int i = 1; i < 24; i++)
                {
                    if (d.RH.HasValue && d.C02.HasValue)
                    {
                        break;
                    }
                    else
                    {
                        qTime = qTime.AddHours(-1 * 1);
                    }
                    d = client.GetZdzData("K4501", string.Format("{0}:00:00", qTime.ToString("yyyy-MM-dd HH")).ToDateTime());

                }
                ViewBag.QueryZdzTime = qTime.ToString("yyyy-MM-dd HH");
                if (d != null)
                {
                    ViewBag.Total = d.Total.HasValue ? d.Total.Value : 0;
                    ViewBag.Photosynthesis = d.Photosynthesis.HasValue ? d.Photosynthesis.Value : 0;
                    ViewBag.RH = d.RH.HasValue ? d.RH.Value : 0;
                    ViewBag.C02 = d.C02.HasValue ? d.C02.Value : 0;
                    ViewBag.T5 = d.T5.HasValue ? d.T5.Value / 10 : 0;
                    ViewBag.T10 = d.T10.HasValue ? d.T10.Value / 10 : 0;
                    ViewBag.T20 = d.T20.HasValue ? d.T20.Value / 10 : 0;
                    ViewBag.SW10 = d.SW10.HasValue ? d.SW10.Value / 10 : 0;
                    ViewBag.SW30 = d.SW30.HasValue ? d.SW30.Value / 10 : 0;
                }
            }
            catch (Exception ex)
            {
                _logger.Write(ex.StackTrace);
            }


            return View();
        }

        public ActionResult QueryZdzData()
        {
            var req = HttpContext.Request;
            var stationid = req.QueryString.AllKeys.Contains("stationid") ? req.QueryString["stationid"] : "";
            var querytime = req.QueryString.AllKeys.Contains("querytime") ? req.QueryString["querytime"] : "";
            var begintime = querytime.ToDateTime(DateTime.Now);
            try
            {
                var client = new Sxqx.Net.Wxzdz.WxzdzWebServiceSoapClient();
                var d = client.GetZdzData(stationid, begintime);
                return Content(Newtonsoft.Json.JsonConvert.SerializeObject(d));
            }
            catch (Exception ex)
            {
                _logger.Write(ex.StackTrace);
            }
            return Content("");
        }
        public ActionResult SyqxWeatherData()
        {
            var req = HttpContext.Request;
            var stationid = req.QueryString.AllKeys.Contains("stationid") ? req.QueryString["stationid"] : "";
            var type = req.QueryString.AllKeys.Contains("type") ? req.QueryString["type"] : "";
            var querytime = req.QueryString.AllKeys.Contains("querytime") ? req.QueryString["querytime"] : "";
            var begintime = querytime.ToDateTime(DateTime.Now).Date;
            var endtime = querytime.ToDateTime(DateTime.Now).Date.AddHours(24);

            var ret = new WeatherChartDataResult();

            try
            {
                var client = new Sxqx.Net.Wxzdz.WxzdzWebServiceSoapClient();
                var list = client.GetWxzdzOrderData(stationid, type, begintime, endtime);
                foreach (var l in list)
                {
                    ret.Times.Add(l.observtime.ToString("yyyyMMddHH"));
                    switch (type)
                    {
                        case "10SW":
                        case "30SW":
                        case "0.5T":
                        case "1.0T":
                        case "2.0T":

                            ret.Values.Add(l.item.HasValue ? l.item.Value / 10 : 0);
                            break;
                        default:
                            ret.Values.Add(l.item.HasValue ? l.item.Value : 0);
                            break;
                    }

                }


            }
            catch (Exception ex)
            {
                _logger.Write(ex.StackTrace);
            }
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(ret));
        }

        #endregion
    }
}
